<template>
  <div class="example-list">
    <!-- 顶部标题栏 -->
    <div class="header">
      <span class="title">内容搜索</span>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索gists..."
        :prefix-icon="Search"
        clearable
        size="small"
      />
    </div>
    
    <!-- 层级列表 -->
    <div class="tree-container">
      <div 
        v-for="category in treeData"
        :key="category.key"
        class="tree-item"
      >
        <!-- 分类标题 -->
        <div 
          class="category-header"
          :class="{ expanded: category.expanded }"
          @click="toggleCategory(category)"
        >
          <el-icon class="expand-icon">
            <ArrowDown v-if="category.expanded" />
            <ArrowRight v-else />
          </el-icon>
          <span class="category-name">{{ category.name }}</span>
        </div>
        
        <!-- 子项目列表 -->
        <div 
          v-if="category.expanded"
          class="sub-items"
        >
          <div 
            v-for="gist in category.items"
            :key="gist.id"
            class="sub-item"
            :class="{ active: currentGistId === gist.id }"
            @click="selectGist(gist)"
          >
            <span class="item-name">{{ gist.description || '未命名' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!hasData" class="empty-state">
        <span>暂无数据</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { Search, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElSkeleton } from 'element-plus'
import { request } from '@/utils/octokit'
import dayjs from 'dayjs'

const store = useStore()

// 响应式数据
const searchKeyword = ref('')
const currentGistId = ref('')
const loading = ref(false)
const gistList = ref([])

// 树形数据结构
const treeData = ref([
  {
    key: 'recent',
    name: '最近',
    expanded: true,
    items: []
  },
  {
    key: 'public',
    name: '公开',
    expanded: false,
    items: []
  },
  {
    key: 'private',
    name: '私有',
    expanded: false,
    items: []
  },
  {
    key: 'analysis',
    name: '分析',
    expanded: false,
    items: []
  },
  {
    key: 'initialization',
    name: '初始化',
    expanded: false,
    items: []
  }
])

// 计算属性
const hasData = computed(() => {
  return treeData.value.some(category => category.items.length > 0)
})

// 方法
const toggleCategory = (category) => {
  category.expanded = !category.expanded
}

const selectGist = async (gist) => {
  try {
    currentGistId.value = gist.id
    loading.value = true
    
    // 获取gist详情
    const { data } = await request(`GET /gists/${gist.id}`)
    
    // 检查是否有coderun.json文件
    if (data.files['coderun.json']) {
      const codeData = JSON.parse(data.files['coderun.json'].content)
      store.commit('setEditData', codeData)
      store.commit('setCodeTitle', codeData.title || gist.description || '未命名')
    } else {
      // 如果没有coderun.json，尝试从其他文件构建
      const codeData = buildCodeDataFromGist(data)
      store.commit('setEditData', codeData)
      store.commit('setCodeTitle', gist.description || '未命名')
    }
    
    ElMessage.success(`已加载：${gist.description || '未命名'}`)
    
  } catch (error) {
    console.error('加载gist失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const buildCodeDataFromGist = (gistData) => {
  const files = gistData.files
  const codeData = {
    config: {
      codeTheme: 'OneDarkPro',
      pageThemeSyncCodeTheme: true,
      openAlmightyConsole: false,
      autoRun: false,
      layout: 'newDefault',
      keepPreviousLogs: true,
      codeFontSize: 16
    },
    title: gistData.description || '未命名',
    code: {
      HTML: { language: 'html', content: '', resources: [] },
      CSS: { language: 'css', content: '', resources: [] },
      JS: { language: 'javascript', content: '', resources: [] },
      VUE: { language: 'vue2', content: '', resources: [] }
    }
  }
  
  // 根据文件名分配内容
  Object.keys(files).forEach(filename => {
    const file = files[filename]
    const content = file.content || ''
    
    if (filename.endsWith('.html') || filename === 'index.html') {
      codeData.code.HTML.content = content
    } else if (filename.endsWith('.css')) {
      codeData.code.CSS.content = content
    } else if (filename.endsWith('.js') || filename.endsWith('.javascript')) {
      codeData.code.JS.content = content
    } else if (filename.endsWith('.vue')) {
      codeData.code.VUE.content = content
    }
  })
  
  return codeData
}

const categorizeGists = (gists) => {
  const recent = []
  const publicGists = []
  const privateGists = []
  const analysis = []
  const initialization = []
  
  const sevenDaysAgo = dayjs().subtract(7, 'day')
  
  gists.forEach(gist => {
    // 最近7天的gists
    if (dayjs(gist.updated_at).isAfter(sevenDaysAgo)) {
      recent.push(gist)
    }
    
    // 按公开/私有分类
    if (gist.public) {
      publicGists.push(gist)
    } else {
      privateGists.push(gist)
    }
    
    // 根据描述或文件名分类
    const description = (gist.description || '').toLowerCase()
    const filenames = Object.keys(gist.files || {}).map(name => name.toLowerCase())
    
    if (description.includes('分析') || description.includes('analysis') || 
        filenames.some(name => name.includes('分析') || name.includes('analysis'))) {
      analysis.push(gist)
    }
    
    if (description.includes('初始化') || description.includes('init') || 
        filenames.some(name => name.includes('初始化') || name.includes('init'))) {
      initialization.push(gist)
    }
  })
  
  // 更新树形数据
  treeData.value[0].items = recent
  treeData.value[1].items = publicGists
  treeData.value[2].items = privateGists
  treeData.value[3].items = analysis
  treeData.value[4].items = initialization
}

const loadGists = async () => {
  try {
    loading.value = true
    const { data } = await request('GET /gists', {
      page: 1,
      per_page: 50
    })
    gistList.value = data
    categorizeGists(data)
  } catch (error) {
    console.error('获取gists失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadGists()
})

// 监听store中的githubToken变化
watch(() => store.state.githubToken, (newToken) => {
  if (newToken) {
    loadGists()
  }
})
</script>

<style scoped lang="less">
.example-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  color: #ffffff;
  
  .header {
    height: 40px;
    background: linear-gradient(90deg, #2d3748 0%, #4a5568 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #4a5568;
    
    .title {
      font-size: 14px;
      font-weight: 500;
      color: #ffffff;
    }
  }
  
  .search-bar {
    padding: 12px 16px;
    border-bottom: 1px solid #4a5568;
    background: #2d3748;
    
    .el-input {
      width: 100%;
      
      :deep(.el-input__wrapper) {
        background: #1e1e1e;
        border: 1px solid #4a5568;
        box-shadow: none;
        
        &:hover {
          border-color: #63b3ed;
        }
        
        &.is-focus {
          border-color: #63b3ed;
          box-shadow: 0 0 0 1px #63b3ed;
        }
      }
      
      :deep(.el-input__inner) {
        color: #ffffff;
        
        &::placeholder {
          color: #a0aec0;
        }
      }
      
      :deep(.el-input__prefix) {
        color: #a0aec0;
      }
    }
  }
  
  .tree-container {
    flex: 1;
    overflow-y: auto;
    padding: 8px 0;
    
    .tree-item {
      .category-header {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        cursor: pointer;
        transition: background-color 0.2s ease;
        
        &:hover {
          background: #2d3748;
        }
        
        .expand-icon {
          width: 16px;
          height: 16px;
          margin-right: 8px;
          color: #a0aec0;
          transition: transform 0.2s ease;
        }
        
        .category-name {
          font-size: 13px;
          color: #ffffff;
          font-weight: 500;
        }
        
        &.expanded {
          .expand-icon {
            transform: rotate(90deg);
          }
        }
      }
      
      .sub-items {
        .sub-item {
          display: flex;
          align-items: center;
          padding: 6px 16px 6px 40px;
          cursor: pointer;
          transition: background-color 0.2s ease;
          
          &:hover {
            background: #2d3748;
          }
          
          &.active {
            background: #3182ce;
            color: #ffffff;
          }
          
          .item-name {
            font-size: 12px;
            color: #e2e8f0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
    
    .loading-state {
      padding: 20px 16px;
    }
    
    .empty-state {
      padding: 40px 16px;
      text-align: center;
      color: #a0aec0;
      font-size: 12px;
    }
  }
}

/* 滚动条样式 */
.tree-container::-webkit-scrollbar {
  width: 6px;
}

.tree-container::-webkit-scrollbar-track {
  background: transparent;
}

.tree-container::-webkit-scrollbar-thumb {
  background: #4a5568;
  border-radius: 3px;
}

.tree-container::-webkit-scrollbar-thumb:hover {
  background: #718096;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-skeleton__item) {
  background: #2d3748;
}

:deep(.el-skeleton__text) {
  background: #2d3748;
}
</style> 